package com.cumt.websocket;

import javax.websocket.Session;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by caicf on 2017/1/11.
 */
public class WsSessionUtil {

    private static final Map<String, Session> clients = new ConcurrentHashMap<>();

    public static void put(String path, Session session) {
        clients.put(path, session);
    }

    public static Session get(String path) {
        return clients.get(path);
    }

    public static void remove(String path) {
        clients.remove(path);
    }

    /**
     * 判断是否有连接
     *
     * @return
     */
    public static boolean hasConnection(String path) {
        return clients.containsKey(path);
    }

    /**
     * 将数据传回客户端
     * 异步的方式
     *
     * @param path
     * @param message
     */
    public static void sendMessage(String path, String message) {
        if (WsSessionUtil.hasConnection(path)) {
            WsSessionUtil.get(path).getAsyncRemote().sendText(message);
        } else {
            throw new NullPointerException(WsSessionUtil.get(path) + " Connection does not exist");
        }
    }

    /**
     * 广播：向所有在线的客户端发送消息
     *
     * @param message
     */
    public static synchronized void broadcast(String message) {
        Set<String> strings = clients.keySet();
        for (String string : strings) {
            clients.get(string).getAsyncRemote().sendText(message);
        }
    }
}
